package Structures;

public class BinaryTree {
    /**
     * 从线性表构建二叉树
     *
     * @param elements 存储各结点值的线性表
     * @param rootIdx  当前构建的结点在线性表中的索引
     * @return 二叉树根结点的引用
     */
    public static TreeNode constructBinaryTree(Integer[] elements, int rootIdx) {
        TreeNode node = new TreeNode(elements[rootIdx]);
        int leftIdx = rootIdx * 2 + 1;
        if (leftIdx < elements.length && elements[leftIdx] != null) // 存在左子结点
            node.left = constructBinaryTree(elements, leftIdx);
        int rightIdx = leftIdx + 1;
        if (rightIdx < elements.length && elements[rightIdx] != null) {
            node.right = constructBinaryTree(elements, rightIdx);
        }

        return node;
    }

    public static TreeNode constructBinaryTree(Integer[] elements) {
        return constructBinaryTree(elements, 0);
    }
}
